package com.chinawayltd.ews.sample.manager.redis.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.chinawayltd.ews.sample.manager.redis.TokenCacheManager;
import com.chinawayltd.ews.sample.model.openApi.UserDTO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * @program: greeProject
 * @description:
 * @author: xiazj
 * @create: 2018-05-16 12:18
 **/
@Service
public class TokenCacheManagerRedisImpl implements TokenCacheManager {

    private final String REDIS_TOKEN_KEY_PREFIX = "_TOKEN:";
    private final int REDIS_TOKEN_INVALID_SECONDS = 60 * 5;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    public void setTokenUser(String token, UserDTO user) {
        if(StringUtils.isBlank(token)){
            throw new NullPointerException("token must be not blank!");
        }else if(user == null){
            throw new NullPointerException("user must be not blank!");
        }
        stringRedisTemplate.opsForValue().set(REDIS_TOKEN_KEY_PREFIX + token, JSONObject.toJSONString(user),REDIS_TOKEN_INVALID_SECONDS, TimeUnit.SECONDS);
    }

    public UserDTO getUserByToken(String token) {
        if(StringUtils.isBlank(token)){
            throw new NullPointerException("token must be not blank!");
        }
        UserDTO result = null;
        Object obj = stringRedisTemplate.opsForValue().get(REDIS_TOKEN_KEY_PREFIX + token);
        if(obj != null){
            String data = obj.toString();
            result = JSON.parseObject(data, UserDTO.class);
        }
        return result;
    }

    public void deleteUserByToken(String token) {
        if(StringUtils.isBlank(token)){
            throw new NullPointerException("token must be not blank!");
        }
        stringRedisTemplate.delete(REDIS_TOKEN_KEY_PREFIX + token);
    }

}
